<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link href="jquery-mobile/jquery.mobile-1.1.1.min.css" rel="stylesheet" type="text/css"/>
		<link href="css/styles.css" rel="stylesheet" type="text/css"/>

		<script src="jquery-mobile/jquery.js" type="text/javascript"></script>
		<script src="js/functions.js" type="text/javascript"></script>
		<script src="jquery-mobile/jquery.mobile-1.1.1.min.js" type="text/javascript"></script>
		<script src="js/cordova-1.9.0.js" type="text/javascript"></script>
		<script src="js/loadingIndicator.js" type="text/javascript"></script>

		<script type="text/javascript"
		src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJdC3CQ8R7WRBANw0QRgQjeWQrx08p1Gc&libraries=places&sensor=true"></script>

		<script type="text/javascript">
			document.addEventListener("deviceready", onDeviceReady, false);
			function onDeviceReady(e) {
				//show loading dialog
				window.plugins.loadingIndicator.show();
				document.addEventListener("backbutton", onBackButton, false);
			}

			function onBackButton(e) {
				e.preventDefault();
				navigator.app.backHistory();

			}
		</script>

		<meta name="viewport" content="width=device-width, initial-scale=1">

	</head>

	<body>
		<!--places page-->
		<div data-role="page" id="places">
			<div data-role="header" class="purple-blue-title-bar" data-backbtn="false">
				<span class="ui-btn-left"><a class="goback_button" onClick="navigator.app.backHistory();"></a></span>
				<h1>Places</h1>
				<div data-role="navbar">
					<ul>
						<li>
							<a href="javascript:fetch_places('restaurant+bar');" id="food_tab">Restaurant / Bar</a>
						</li>
						<li>
							<a href="javascript:fetch_places('hotel');" id="hotel_tab">Hotel</a>
						</li>
						<li>
							<a href="javascript:fetch_places('club+pub');" id="club_tab">Club / Pub</a>
						</li>
					</ul>
				</div><!-- /navbar -->
			</div>

			<div data-role="content">
				<ul data-role="listview" data-autodividers="true" data-theme="d" id="result_list" data-split-icon="info" data-split-theme="d">

				</ul>
			</div>

		</div>

	<script type="text/javascript">
		$(document).live('pageinit', function() {
			fetch_places('restaurant+bar');
		});

		$('#food_tab').live('click', function() {
			//$(this).addClass('ui-btn-active');
			window.plugins.loadingIndicator.show();
		});

		$('#hotel_tab').live('click', function() {
			//$(this).addClass('ui-btn-active');
			window.plugins.loadingIndicator.show();
		});
		$('#club_tab').live('click', function() {
			//$(this).addClass('ui-btn-active');
			window.plugins.loadingIndicator.show();
		});
		function fetch_places(keyword) {
			//get user location
			if (navigator.geolocation) {
				var list_content = "";
				navigator.geolocation.getCurrentPosition(function(position) {
					var pos = position.coords.latitude + "," + position.coords.longitude;
					$.getJSON("https://maps.googleapis.com/maps/api/place/search/json?location=" + pos + "&keyword=" + keyword + "&rankby=distance&sensor=true&key=AIzaSyCJdC3CQ8R7WRBANw0QRgQjeWQrx08p1Gc", function(data) {
						var dataToString = JSON.stringify(data);
						var status = data.status;
						if (status === "OK") {

							var results = data.results;

							//hide loading dialog
							window.plugins.loadingIndicator.hide();

							//display result
							//determine tab
							var current_tab = "";
							if (keyword === 'restaurant+bar') {
								current_tab = "Restaurant / Bar"
							}
							if (keyword === 'hotel') {
								current_tab = "Hotel"
							}
							if (keyword === 'club+pub') {
								current_tab = "Club / Pub"
							}
							list_content += '<li data-role="list-divider">' + current_tab + ' Near Me</li>';

							var ref;
							//$('#result_list').append('<li data-role="list-divider">Places near you</li>');
							for (var i = 0; i < results.length; i++) {
								ref = JSON.stringify(results[i].reference);

								list_content += "<li>" + "<a href=\"#\" rel=\"external\" data-ajax=\"false\" >" + "<img src=" + JSON.stringify(results[i].icon) + "></img>" + "<h3>" + JSON.stringify(results[i].name) + "</h3>";
								if ( typeof JSON.stringify(results[i].rating) !== "undefined") {
									list_content += "<p>Rating: " + JSON.stringify(results[i].rating) + " /5 </p>";
								}
								var dest = JSON.stringify(results[i].geometry.location.lat) + "," + JSON.stringify(results[i].geometry.location.lng);
								/*$.getJSON("http://maps.googleapis.com/maps/api/distancematrix/json?origins="+pos+"&destinations="+dest+"&mode=walking&sensor=true",function(data){
								 var dataToString = JSON.stringify(data);
								 var results = JSON.parse(dataToString).results;
								 });*/

								list_content += "<p>" + calcDistance(position.coords.latitude, position.coords.longitude, JSON.stringify(results[i].geometry.location.lat), JSON.stringify(results[i].geometry.location.lng)) + " km</p>";

								list_content += "</a>" + "<a href=\"" + "place_details.html?ref=" + ref.replace(/"/g, '') + "&myLat="+position.coords.latitude+"&myLng="+position.coords.longitude+"\" data-ajax=\"false\"></a>" + "</li>";
							}
							//console.log('show list content:\n'+list_content);

							$('#result_list').html(list_content);
							$('#result_list').listview("refresh");
						}else{
							alert('error: '+status);
						}
					}, "json");

				});

			} else {

				window.plugins.loadingIndicator.hide();

				alert('Please turn on geolocation services');
			}

		}

		function calcDistance(lat1, lon1, lat2, lon2) {
			//Radius of the earth in:  1.609344 miles,  6371 km  | var R = (6371 / 1.609344);
			var R = 3958.7558657440545;
			// Radius of earth in Miles
			var dLat = toRad(lat2 - lat1);
			var dLon = toRad(lon2 - lon1);
			var a = (1.0 - Math.cos(dLat)) / 2.0 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * (1.0 - Math.cos(dLon)) / 2.0;
			var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			return (R * c).toFixed(2);

		}

		function toRad(Value) {
			/** Converts numeric degrees to radians */
			return Value * Math.PI / 180;
		}
	</script>
	</body>
</html>
